package com.pets.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pets.entity.Users;
import com.pets.mapper.UsersMapper;
import com.pets.service.IUsersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pets.utils.Result;
import com.pets.viewModels.FileViewModels;
import com.pets.viewModels.UsersViewModels;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author 啦啦啦
 * @since 2024-04-09
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements IUsersService {

    @Autowired
    private UsersMapper usersMapper;

    /**
     * 判断邮箱是否正确
     */
    private static final Pattern EMAIL_PATTERN =
            Pattern.compile("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
                    + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");

    public static boolean isValidEmail(String email) {
        return EMAIL_PATTERN.matcher(email).matches();
    }

    /**
     * 判断手机号是否正确
     *
     * @param phoneNumber
     * @return
     */
    public static boolean isValidPhoneNumber(String phoneNumber) {
        // 中国手机号的正则表达式
        String regex = "^1[3-9]\\d{9}$";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(phoneNumber);
        return matcher.matches();
    }

    @Override
    public Result login(String username, String password, HttpSession session) {
        if (username == null || username.isEmpty() || password == null || password.isEmpty()) {
            return Result.fail("不能为空");
        }
        LambdaQueryWrapper<Users> usersQueryWrapper = new LambdaQueryWrapper<>();
        // 使用nested来包裹OR条件，确保它们作为一个整体与其他条件组合
        usersQueryWrapper.nested(wrapper -> {
                wrapper.eq(Users::getUsername, username);
                wrapper.or().eq(Users::getMailbox, username);
                wrapper.or().eq(Users::getPhone, username);
        });
        usersQueryWrapper.eq(Users::getPassword, password);
        Users users = usersMapper.selectOne(usersQueryWrapper);
        if (users != null) {
            if(users.getIsDisable()){
                return Result.fail("该账户已被禁用！", users);
            }
            session.setAttribute("users", users);
            return Result.success("登录成功！", users);
        } else {
            return Result.fail("登录失败！");
        }
    }

    /**
     * 用户注册
     */
    @Override
    public Result register(UsersViewModels usersV) {
        //对象映射器
        ModelMapper modelMapper = new ModelMapper();
        Users users = modelMapper.map(usersV, Users.class);
        if (users.getPassword() == null || users.getPassword().isEmpty()) {
            return Result.fail("未设置密码");
        }
        if ((users.getUsername() == null || users.getUsername().isEmpty())
                && (users.getPhone() == null || users.getPhone().isEmpty())
                && (users.getMailbox() == null || users.getMailbox().isEmpty())) {
            return Result.fail("账号邮箱手机号必须设置一个！");
        }
        if (users.getMailbox() != null && !users.getMailbox().isEmpty()) {
            if (!isValidEmail(users.getMailbox())) {
                return Result.fail("邮箱格式错误！");
            }
        }
        if (users.getPhone() != null && !users.getPhone().isEmpty()) {
            if (!isValidPhoneNumber(users.getPhone())) {
                return Result.fail("手机号格式错误！");
            }
        }
        LambdaQueryWrapper<Users> usersQueryWrapper = new LambdaQueryWrapper<>();
        if (users.getUsername() != null && !users.getUsername().isEmpty()) {
            usersQueryWrapper.or().eq(Users::getUsername, users.getUsername());
        }
        if (users.getMailbox() != null && !users.getMailbox().isEmpty()) {
            usersQueryWrapper.or().eq(Users::getMailbox, users.getMailbox());
        }
        if (users.getPhone() != null && !users.getPhone().isEmpty()) {
            usersQueryWrapper.or().eq(Users::getPhone, users.getPhone());
        }
        if (usersMapper.selectOne(usersQueryWrapper) != null) {
            return Result.fail("账号或邮箱或手机号重复！");
        }
        users.setIntegral(0);//积分
        users.setIsDisable(false);//是否禁用
        return usersMapper.insert(users) > 0 ? Result.success("创建成功！") : Result.fail("创建失败！");
    }

    /**
     * 删除用户
     *
     * @param id
     * @return
     */
    @Override
    public Result deleteById(Integer id) {
        return usersMapper.deleteById(id) > 0 ? Result.fail("删除成功！") : Result.fail("删除失败！");
    }

    @Override
    public Result updateData(Users users) {
        if (users.getPassword() == null || users.getPassword().isEmpty()) {
            return Result.fail("未设置密码");
        }
        if (users.getUsername() == null && users.getUsername().isEmpty()
                && users.getPhone() == null && users.getPhone().isEmpty()
                && users.getMailbox() == null && users.getMailbox().isEmpty()) {
            return Result.fail("账号邮箱手机号必须设置一个！");
        }
        if (users.getMailbox() != null && !users.getMailbox().isEmpty()) {
            if (!isValidEmail(users.getMailbox())) {
                return Result.fail("邮箱格式错误！");
            }
        }
        if (users.getPhone() != null && !users.getPhone().isEmpty()) {
            if (!isValidPhoneNumber(users.getPhone())) {
                return Result.fail("手机号格式错误！");
            }
        }
        LambdaQueryWrapper<Users> usersQueryWrapper = new LambdaQueryWrapper<>();
        // 使用nested来包裹OR条件，确保它们作为一个整体与其他条件组合
        usersQueryWrapper.nested(wrapper -> {
            if (users.getUsername() != null && !users.getUsername().isEmpty()) {
                wrapper.eq(Users::getUsername, users.getUsername());
            }
            if (users.getMailbox() != null && !users.getMailbox().isEmpty()) {
                wrapper.or().eq(Users::getMailbox, users.getMailbox());
            }
            if (users.getPhone() != null && !users.getPhone().isEmpty()) {
                wrapper.or().eq(Users::getPhone, users.getPhone());
            }
        });
        usersQueryWrapper.ne(Users::getUserId, users.getUserId());
        List<Users> usersList = usersMapper.selectList(usersQueryWrapper);
        if (usersList != null && usersList.size() > 0) {
            return Result.fail("账号或邮箱或手机号重复！");
        }
        //判断是否设置管理员
        if(users.getIsAdministrators()==null)
            users.setIsAdministrators(false);
        return usersMapper.updateById(users) > 0 ? Result.success("修改成功！") : Result.fail("修改失败！");
    }

    @Override
    public Result selectById(Integer id) {
        Users users = usersMapper.selectById(id);
        return users != null ? Result.success("查询成功！", users) : Result.fail("未查询到用户");
    }

    @Override
    public Result selectPage(Integer page, Integer pageSize, String username, String nickname, String mailbox, String phone, Boolean isDisable) {
        final LambdaQueryWrapper<Users> lqw = new LambdaQueryWrapper<>();
        lqw.like(nickname != null && !nickname.isEmpty(), Users::getNickname, nickname)
                .like(username != null && !username.isEmpty(), Users::getUsername, username)
                .like(phone != null && !phone.isEmpty(), Users::getPhone, phone)
                .eq(isDisable != null, Users::getIsDisable, isDisable)
                .like(mailbox != null && !mailbox.isEmpty(), Users::getMailbox, mailbox);
        IPage<Users> Page = new Page<>(page, pageSize);
        IPage<Users> IPage = usersMapper.selectPage(Page, lqw);
        return Result.success("查询成功", IPage);
    }

    /**
     * 判断是否有积分
     */
    @Override
    public boolean isIntegral(Integer userId) {
        Users users = usersMapper.selectById(userId);
        if(users==null){
            return false;
        }
        if(users.getIntegral()<=0){
            return false;
        }
        return true;
    }


}
